package com.ww.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MysqlBackupUtil {
	
	static Logger logger = LoggerFactory.getLogger(MysqlBackupUtil.class);
	
	/**
	 * 使用mysqldump命令在数据库服务器备份数据
	 * @param username
	 * 		用户名
	 * @param password
	 * 		密码
	 * @param dbname
	 * 		数据库名称
	 * @param destPath
	 * 		备份文件路径
	 * @throws IOException
	 */
	public static void backup_mysqldump(String username, String password, String dbname, String destPath) throws IOException {
		logger.info("开始备份数据库");
		Runtime rt = Runtime.getRuntime();
		Calendar cl = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String currentTime = sdf.format(cl.getTime());
		Process p = null;
		InputStream in = null;
		OutputStream ops = null;
		
		try {
			logger.info("exec :" + "cmd /c mysqldump -u"+username+" -p" + password + " " + dbname + ">" + destPath + File.separatorChar + currentTime + ".sql");
			p = rt.exec("cmd /c mysqldump -u"+username+" -p" + password + " " + dbname + ">" + destPath + File.separatorChar + currentTime + ".sql");
			ops = p.getOutputStream();
			in = p.getInputStream();
			logger.info(in.toString());
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} finally {
			in.close();
			ops.close();
		}
	}
}
